package basic;


// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 
//

import java.io.UnsupportedEncodingException;

import java.io.IOException;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


import flexibility.userData;

import ocsf.server.*;

import com.sun.rowset.CachedRowSetImpl;
/**
 * This class overrides some of the methods in the abstract superclass in order
 * to give more functionality to the server.
 * 
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;re
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer {
 // Class variables *************************************************
 mysqlConnection connect = new mysqlConnection(); // create object of
 // data base
 Connection conn = connect.connectToDB(); // connect to data base and
 // returns data base object
 // mysqlConnection connect = new mysqlConnection();
 // connect.connectToDB();
 /**
  * The default port to listen on.
  */
 final public static int DEFAULT_PORT = 5555;

 // Constructors ****************************************************

 /**
  * Constructs an instance of the echo server.
  * 
  * @param port
  *            The port number to connect on.
  */
 public EchoServer(int port) {
  super(port);
 }
 


 // Instance methods ************************************************

 /**
  * This method handles any messages received from the client.
  * 
  * @param msg
  *            The message received from the client.
  * @param client
  *            The connection from which the message originated.
  */
 public void handleMessageFromClient(userData msg, ConnectionToClient client) {
  String query;//will hold the sql query
  Boolean writeResult = null;
  Boolean uploadResult = null;
  CachedRowSetImpl crs = null;//this object will hold the query results
  try { 
   crs = new CachedRowSetImpl();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  queries createQuery = new queries();// create queries object
  executeQuery execute = new executeQuery();

  query = createQuery.identifyQuery(msg);// creates the query
  System.out.println(query);
  if (createQuery.getType() == 0) {
   writeResult = execute.writeToDataBase(conn, query);
   if(writeResult==false){
	   this.sendToClient(crs,client);// this.sendToAllClients(crs);// this.sendToAllClients(crs);ROMAN***********************************************
   }
   //this.sendToAllClients(writeResult);
  }
  if (createQuery.getType() == 1) {
   crs = execute.readFromDataBase(conn, query);
   this.sendToClient(crs,client); //this.sendToAllClients(crs);  //ROMAN***********************************************
  }

  //Case the action is upload file
  if  (createQuery.getType() == 2) {
   uploadResult=execute.uploadFileToDataBase(conn, query,msg);
   if(uploadResult==true){
    
	   this.sendToClient(crs,client);// this.sendToAllClients(crs);// //ROMAN***********************************************
     
   }
  
   //this.sendToAllClients(crs);
  }

  
  if(createQuery.getType() == 3){//this is to identify the client ip
   Thread[] previousClient;
   previousClient = this.getClientConnections();
   for(int i =0; i <= previousClient.length; i++){
    if(previousClient[i].toString().contains(msg.getData(2).toString())){
     try {
    	 this.sendToClient(null,client);// this.sendToAllClients(null);
      ((ConnectionToClient)previousClient[i]).close();
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  }


 }

 public  String getServerTime(){
	 String currentDate = null;
	 SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
	 Calendar reportTime = Calendar.getInstance();
	 currentDate = formatter.format(reportTime.getTime());
	 System.out.println("the time onthe server is "+ currentDate);
	 return currentDate;
 }
 
 /**
  * This method overrides the one in the superclass. Called when the server
  * starts listening for connections.
  */
 protected void serverStarted() {
  System.out.println("Server is listening for connections on port "
    + getPort());
 }

 /**
  * This method overrides the one in the superclass. Called when the server
  * stops listening for connections.
  */
 protected void serverStopped() {
  System.out.println("Server has stopped listening for connections.");
 }

 // Class methods ***************************************************

 /**
  * This method is responsible for the creation of the server instance (there
  * is no UI in this phase).
  * 
  * @param args
  *            [0] The port number to listen on. Defaults to 5555 if no
  *            argument is entered.
  */
 public static void main(String[] args) {
  int port = 0; // Port to listen on

  try {
	
   port = Integer.parseInt(args[0]); // Get port from command line
   
  } catch (Throwable t) {
   port = DEFAULT_PORT; // Set port to 5555
  }

  EchoServer sv = new EchoServer(port);
 
  try {
   sv.listen(); // Start listening for connections
  } catch (Exception ex) {
   System.out.println("ERROR - Could not listen for clients!");
  }
 }
}
// End of EchoServer class